﻿/************************************************************************
 * CoreDES - A small and core library for discrete event systems
 * Copyright (C) 2012-2013 Ali Khalili (khalili_DOT_ir_@SIGN_gmail_DOT_com)
 * **********************************************************************
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License (LGPL) published 
 * by the Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version. This program is distributed without any
 * warranty. See the GNU Lesser General Public License for more details. 
 * ***********************************************************************
 * File         :     Simulator.cs
 * Description  :     The base class for all simulators
 * Change log   :     -Oct 2013:  Initial draft
 * To Do        :     rename the file to BaseSimulator, complete the code an
 *                    use it for the simulators everywhere
 ************************************************************************/
using System;
using System.Collections.Generic;
using System.Threading;

namespace CoreDES.Simulation
{
    /// <summary>
    /// The base class for all simulators
    /// </summary>
    public abstract class BaseSimulator<ACTIONTYPE>
    {
        #region -=[ Internal properties ]=-
        /// <summary>
        /// The current step in this round of execution
        /// </summary>
        protected uint step;

        /// <summary>
        /// 
        /// </summary>
        protected uint remainingSteps;


        protected TimeSpan simTime;

        protected Thread runningthread, watchdog;

        /// <summary>
        /// A mutex for synchronization
        /// </summary>
        
		//Mutex m;

        ManualResetEvent _suspendRunningThread;

        //enum SimulatorStatusEnum { RUNNING, STOPPED };
        //SimulatorStatusEnum simStat;


        #endregion

        /// <summary>
        /// Constructor
        /// </summary>
        protected BaseSimulator()
        {
            remainingSteps = 0;
            step = 0;
            simTime = TimeSpan.Zero;
            runningthread = new Thread(RunningThread);
            //m = new Mutex();
            //simStat = SimulatorStatusEnum.STOPPED;
            paused = false;
            _suspendRunningThread = new ManualResetEvent(true);
        }

        /// <summary>
        /// Total simulation time
        /// </summary>
        public double SimulationTime
        {
            get
            {
                return simTime.TotalMilliseconds;
            }
        }

        /// <summary>
        /// Number of executed actions
        /// </summary>
        public int Step
        {
            get
            {
                return (int)step;
            }
        }

        #region -=[ Abstract methods ]=-

        /// <summary>
        /// abstract method to select an action
        /// </summary>
        public abstract ACTIONTYPE GetNextAction();

        /// <summary>
        /// Execute the next action
        /// <param name="act"></param>
        /// </summary>
        public abstract void ExecuteAction(ACTIONTYPE act);

        /// <summary>
        /// Reset the simulation
        /// </summary>
        public abstract void Reset();


        #endregion

        /// <summary>
        /// Check wheather the pause condition holds or not
        /// </summary>
        /// <returns></returns>
        protected virtual bool PauseCondition()
        {
            return false;
        }

        /// <summary>
        /// Check wheather the end condition holds or not
        /// </summary>
        /// <returns></returns>
        protected virtual bool EndCondition()
        {
            return false;
        }



        /// <summary>
        /// The main loop (selecting an action and executing it)
        /// </summary>
        protected virtual void RunningThread()
        {
            if (step == 0)
                Reset();

            while (true)
            {
                //* check whether we should pause or not!
                _suspendRunningThread.WaitOne(Timeout.Infinite);


                if (remainingSteps < 1)
                {
                    //* return because of the remaining step is already zero!
                    return;
                }
                remainingSteps--;
                step++;

                //* select an action
                ACTIONTYPE selectedAction = GetNextAction();
                //* check whether any action is selcted or not!
                if (selectedAction == null)
                {
                    //* return because no action is selected
                    return;
                }

                //* execute the selected action
                ExecuteAction(selectedAction);

                if (PauseCondition())
                {
                    //* return because of a pause condition
                    return;
                }

            }
        }

        bool paused;

        /// <summary>
        /// Pause the simulation thread
        /// </summary>
        public virtual void Puase()
        {
            if (runningthread.ThreadState == ThreadState.Running
                  ||
                  runningthread.ThreadState == ThreadState.WaitSleepJoin)
            {
                //runningthread.Suspend();
                _suspendRunningThread.Reset();
            }
            paused = true;
        }

        /// <summary>
        /// Resume the simulation thread when it is paused
        /// </summary>
        public virtual void Resume()
        {
            if (!paused)
                return;
            if (runningthread.ThreadState == ThreadState.WaitSleepJoin)
            {
                _suspendRunningThread.Set();
            }
            paused = false;
        }



        /// <summary>
        /// Run (or continue to run) the simulation thread
        /// </summary>
        /// <param name="numberOfStep">an specific number of action execution (by default, it is infinity)</param>
        public virtual void Run(uint numberOfStep = int.MaxValue)
        {
            remainingSteps = numberOfStep;
        }

    }
}
